/**
 * 相册HTML生成器
 * 根据处理后的数据生成主相册和时间轴的HTML结构
 */

class AlbumGenerator {
    constructor(processor, config) {
        this.processor = processor;
        this.config = config;
    }

    /**
     * 生成主相册HTML
     * @returns {string} HTML字符串
     */
    generateMainCarousel() {
        const images = this.processor.getAllImages();
        let html = '';

        images.forEach((image, index) => {
            const imageUrl = this.getFullImageUrl(image.url);
            const cssClasses = [
                'carousel-cell',
                'main-carousel-cell',
                image.cssClass
            ];

            if (image.isFirstOfYear) {
                cssClasses.push('first-of-year');
                cssClasses.push(`first-of-${image.year}`);
                cssClasses.push(`year-${image.year}`); // 只在第一张图片上添加年份选择器
            }

            html += `
                <div class="${cssClasses.join(' ')}"
                     data-year="${image.year}"
                     data-year-index="${image.yearIndex}"
                     data-global-index="${image.globalIndex}"
                     data-image-id="${image.id}"
                     data-hash="slide-${image.globalIndex}"
                     id="slide-${image.globalIndex}">
                    <div class="image-container">
                        <img class="carousel-image"
                             data-flickity-lazyload="${imageUrl}"
                             alt="${this.escapeHtml(image.title)}"
                             data-title="${this.escapeHtml(image.title)}"
                             data-year="${image.year}">
                        ${this.renderOverlay(image)}
                    </div>
                </div>
            `;
        });

        return html;
    }

    /**
     * 生成时间轴HTML - 每个年份一个cell（可见导航）
     * @returns {string} HTML字符串
     */
    generateTimelineNav() {
        // 使用实际图片数据获取所有年份
        const allImages = this.processor.getAllImages();
        const yearCounts = {};

        allImages.forEach(image => {
            yearCounts[image.year] = (yearCounts[image.year] || 0) + 1;
        });

        const sortedYears = Object.keys(yearCounts).sort();
        let html = '';

        sortedYears.forEach(year => {
            const imageCount = yearCounts[year];
            const cssClasses = [
                'carousel-cell',
                'timeline-cell',
                `timeline-${year}`
            ];

            html += `
                <div class="${cssClasses.join(' ')}"
                     data-year="${year}"
                     data-image-count="${imageCount}"
                     id="timeline-year-${year}">
                    <div class="timeline-top">
                        <span class="timeline-year-text">${year}</span>
                    </div>
                </div>
            `;
        });

        return html;
    }

    /**
     * 获取完整的图片URL
     * @param {string} relativePath 相对路径
     * @returns {string} 完整URL
     */
    getFullImageUrl(relativePath) {
        if (!relativePath) {
            return this.config.fallbackImage;
        }

        // 如果已经是完整URL，直接返回
        if (relativePath.startsWith('http://') || relativePath.startsWith('https://')) {
            return relativePath;
        }

        // 如果是data URL，直接返回
        if (relativePath.startsWith('data:')) {
            return relativePath;
        }

        // 拼接基础URL
        return this.config.baseImageUrl + relativePath;
    }

    /**
     * 根据标题返回简介
     */
    getCaseDescByTitle(title) {
        if (!title) return '';
        const dict = (this.config && this.config.caseDescriptions) || (window && window.caseDescriptions) || {};
        return dict[title] || '';
    }

    /**
     * HTML转义
     * @param {string} text 原始文本
     * @returns {string} 转义后的文本
     */
    /**
     * 按配置渲染 overlay：
     * 0=关闭，1=只标题，2=标题+简介
     */
    renderOverlay(image) {
        const mode = (this.config && this.config.imageOverlayMode) ?? 2;
        if (mode === 0) return '';
        const titleHtml = `<h3 class="image-title">${this.escapeHtml(image.title)}</h3>`;
        if (mode === 1) {
            return `
                <div class="image-overlay">
                    <div class="image-info">
                        ${titleHtml}
                    </div>
                </div>`;
        }
        // 默认模式 2：标题 + 红线 + 简介
        const desc = this.getCaseDescByTitle(image.title) || '';
        const descHtml = desc ? `<div class="image-title-divider"></div><p class="image-desc">${this.escapeHtml(desc)}</p>` : '';
        return `
            <div class="image-overlay">
                <div class="image-info">
                    ${titleHtml}
                    ${descHtml}
                </div>
            </div>`;
    }

    escapeHtml(text) {
        if (!text) return '';

        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    // 去除加载/错误/空状态的 UI 生成，保持最简输出
    generateLoadingState() { return ''; }
    generateErrorState() { return ''; }
    generateEmptyState() { return ''; }

    /**
     * 渲染主相册到DOM
     * @param {string} containerId 容器ID
     */
    renderMainCarousel(containerId = 'main-carousel') {
        const container = document.getElementById(containerId);
        if (!container) {
            console.error(`找不到容器: ${containerId}`);
            return;
        }

        try {
            const images = this.processor.getAllImages();
            // 直接输出（不渲染 loading/错误/空状态 UI）
            container.innerHTML = images && images.length ? this.generateMainCarousel() : '';
        } catch (error) {
            console.error('渲染主相册失败:', error);
            container.innerHTML = '';
        }
    }

    /**
     * 渲染时间轴到DOM
     * @param {string} containerId 容器ID
     */
    renderTimelineNav(containerId = 'timeline-nav') {
        const container = document.getElementById(containerId);
        if (!container) {
            console.error(`找不到容器: ${containerId}`);
            return;
        }

        try {
            const validation = this.processor.validateData();

            if (!validation.isValid) {
                container.innerHTML = '<div class="timeline-error">时间轴加载失败</div>';
                return;
            }

            const timelineYears = this.processor.getTimelineData();
            if (timelineYears.length === 0) {
                container.innerHTML = '<div class="timeline-empty">暂无时间数据</div>';
                return;
            }

            container.innerHTML = this.generateTimelineNav();

        } catch (error) {
            console.error('渲染时间轴失败:', error);
            container.innerHTML = '<div class="timeline-error">时间轴渲染失败</div>';
        }
    }

    /**
     * 渲染完整相册
     */
    renderAlbum() {
        this.renderMainCarousel();
        this.renderTimelineNav();
    }

    /**
     * 生成隐藏代理导航（1:1 映射，每图一个cell，不显示在视觉中）
     * @returns {string} HTML字符串
     */
    generateProxyNav() {
        const images = this.processor.getAllImages();
        let html = '';
        images.forEach((image, index) => {
            html += `
                <div class="carousel-cell proxy-cell"
                     data-year="${image.year}"
                     data-index="${index}"
                     id="proxy-${index}">
                    <div class="proxy-dot"></div>
                </div>
            `;
        });
        return html;
    }

    /**
     * 渲染隐藏代理导航到DOM
     */
    renderProxyNav(containerId = 'timeline-proxy') {
        const container = document.getElementById(containerId);
        if (!container) return;
        container.innerHTML = this.generateProxyNav();
    }

    /**
     * 扩展渲染：主相册、可见时间轴、隐藏代理导航
     */
    renderAlbumWithProxy() {
        this.renderMainCarousel();
        this.renderTimelineNav();
        this.renderProxyNav();
    }

    /**
     * 获取渲染统计信息
     * @returns {Object} 统计信息
     */
    getRenderStats() {
        const stats = this.processor.getStatistics();
        const timelineYears = this.processor.getTimelineData();

        return {
            ...stats,
            timelineYears: timelineYears.length,
            maxTimelineYears: this.config.maxTimelineItems,
            isTimelineTruncated: timelineYears.length < stats.totalYears
        };
    }
}

// 导出类
if (typeof module !== 'undefined' && module.exports) {
    module.exports = AlbumGenerator;
} else {
    // 浏览器环境下，将类添加到全局作用域
    window.AlbumGenerator = AlbumGenerator;
}
